package dao.cms;

import dao.AbstractEntityRepository;
import dao.inte.CmsPageRepository;
import domain.cms.CmsPage;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.persistence.NoResultException;
import java.util.List;

@Singleton
@Transactional
public class CmsPageRepositoryImpl extends AbstractEntityRepository<CmsPage> implements CmsPageRepository {
    public CmsPageRepositoryImpl() {
        super(CmsPage.class);
    }

    @Override
    protected Class<CmsPage> getEntityClass() {
        return CmsPage.class;
    }


    @Transactional(readOnly = true, noRollbackFor = NoResultException.class)
    public CmsPage findByUrl(String url) {
        if (url != null) {
            url = url.toLowerCase();
        }
        CmsPage result = null;
        try {
            result = entityManager.
                    createNamedQuery("CmsPageNew.findByUrl", CmsPage.class).setParameter("url", url).getSingleResult();
        } catch (NoResultException e) {
            result = entityManager.
                    createNamedQuery("CmsPageNew.findByOldUrl", CmsPage.class).setParameter("url", url).getSingleResult();

        }


        return result;
    }

    @Override


    @Transactional(noRollbackFor = NoResultException.class)
    public CmsPage save(CmsPage object) throws Exception {
        object.setUrlIfNull();
        return super.save(object);
    }

    public List<CmsPage> findByTitle(@Named("title") String title) {
        return entityManager.
                createNamedQuery("CmsPageNew.findByTitle", CmsPage.class).setParameter("title", title).
                getResultList();
    }


    public List<CmsPage> findRoots() {
        List resultList = entityManager.
                createNamedQuery("CmsPageNew.findRoots", CmsPage.class).
                getResultList();
        return resultList;
    }

    public List<CmsPage> findChildsByParentId(@Named("parentId") Long parentId) {
        return entityManager.
                createNamedQuery("CmsPageNew.findChildsByParentId", CmsPage.class).setParameter("parentId", parentId).
                getResultList();
    }

    public List<CmsPage> getPublishedSections() {
        List resultList = entityManager.
                createNamedQuery("CmsPageNew.findPublishedSections", CmsPage.class).
                getResultList();

        return resultList;

    }


}
